const db = uniCloud.database()
const jqldb = uniCloud.databaseForJQL()

module.exports = {
	/**
	 * get 获取所有分类
	 */
	async get() {
		try {
			const result = await jqldb.collection('cate').get()
			return {
				errCode: 0,
				errMsg: '获取成功',
				data: result.data
			}
		} catch (error) {
			return {
				errCode: -1,
				errMsg: '获取失败'
			}
		}
	},

	/**
	 * add 添加分类
	 */
	async add(data, role) {
		if (role !== 'admin') {
			return {
				errCode: -1,
				errMsg: '无权限操作'
			}
		}
		if (!data.cate_name) {
			return {
				errCode: -1,
				errMsg: '分类名称不能为空'
			}
		}

		try {
			const result = await db.collection('cate').add({
				cate_name: data.cate_name
			})
			return {
				errCode: 0,
				errMsg: '添加成功',
				id: result.id
			}
		} catch (error) {
			return {
				errCode: -1,
				errMsg: '添加失败'
			}
		}
	},

	/**
	 * update 更新分类
	 */
	async update(data, role) {
		if (role !== 'admin') {
			return {
				errCode: -1,
				errMsg: '无权限操作'
			}
		}
		if (!data._id || !data.cate_name) {
			return {
				errCode: -1,
				errMsg: '参数不完整'
			}
		}

		try {
			await db.collection('cate').doc(data._id).update({
				cate_name: data.cate_name
			})
			return {
				errCode: 0,
				errMsg: '更新成功'
			}
		} catch (error) {
			return {
				errCode: -1,
				errMsg: '更新失败'
			}
		}
	},

	/**
	 * remove 删除分类
	 */
	async remove(id, role) {
		if (role !== 'admin') {
			return {
				errCode: -1,
				errMsg: '无权限操作'
			}
		}
		if (!id) {
			return {
				errCode: -1,
				errMsg: '分类ID不能为空'
			}
		}

		try {
			await db.collection('cate').doc(id).remove()
			return {
				errCode: 0,
				errMsg: '删除成功'
			}
		} catch (error) {
			return {
				errCode: -1,
				errMsg: '删除失败'
			}
		}
	}
}